import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:image/image.dart' as img;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:palette_generator/palette_generator.dart';
import 'package:image_cropper/image_cropper.dart';
import 'dart:typed_data';
import 'dart:convert';

/// 主题类型枚举
enum AppThemeType {
  pinkGradient, // 粉色渐变白（默认）
  darkTheme, // 黑夜主题
  greyGradient, // 灰渐变白主题
  custom, // 自定义主题
}

/// 应用主题配置
class AppThemeConfig {
  final AppThemeType themeType;
  final Color primaryColor;
  final List<Color> gradientColors;
  final String? backgroundImagePath;
  final double backgroundOpacity;
  final bool isDarkMode;
  final Alignment? backgroundAlignment; // 背景图片对齐方式
  final String fontFamily; // 添加字体设置

  const AppThemeConfig({
    this.themeType = AppThemeType.pinkGradient,
    required this.primaryColor,
    required this.gradientColors,
    this.backgroundImagePath,
    this.backgroundOpacity = 0.8,
    this.isDarkMode = false,
    this.backgroundAlignment,
    this.fontFamily = 'Cat', // 默认字体
  });

  /// 创建默认的粉色渐变主题
  factory AppThemeConfig.defaultTheme() {
    final primaryColor = Color(0xFFFF4081); // 粉色
    return AppThemeConfig(
      themeType: AppThemeType.pinkGradient,
      primaryColor: primaryColor,
      gradientColors: [
        primaryColor.withRed((primaryColor.red + 20).clamp(0, 255)),
        primaryColor,
        primaryColor.withBlue((primaryColor.blue + 30).clamp(0, 255)),
      ],
      backgroundOpacity: 0.8,
      isDarkMode: false,
    );
  }

  /// 创建黑夜主题
  factory AppThemeConfig.darkTheme() {
    final primaryColor = Color(0xFF5D6D7E); // 更柔和的深蓝灰色
    return AppThemeConfig(
      themeType: AppThemeType.darkTheme,
      primaryColor: primaryColor,
      gradientColors: [
        Color(0xFF455A64), // 深蓝灰色
        primaryColor,
        Color(0xFF607D8B), // 蓝灰色
      ],
      backgroundOpacity: 0.9,
      isDarkMode: true,
    );
  }

  /// 创建灰渐变白主题
  factory AppThemeConfig.greyGradient() {
    final primaryColor = Color(0xFF78909C); // 更柔和的蓝灰色
    return AppThemeConfig(
      themeType: AppThemeType.greyGradient,
      primaryColor: primaryColor,
      gradientColors: [
        Color(0xFFB0BEC5), // 浅蓝灰色
        primaryColor,
        Color(0xFF546E7A), // 深蓝灰色
      ],
      backgroundOpacity: 0.7,
      isDarkMode: false,
    );
  }

  /// 创建自定义主题
  factory AppThemeConfig.custom({
    required Color primaryColor,
    required List<Color> gradientColors,
    required String backgroundImagePath,
    double backgroundOpacity = 0.8,
    bool isDarkMode = false,
    Alignment? backgroundAlignment,
  }) {
    return AppThemeConfig(
      themeType: AppThemeType.custom,
      primaryColor: primaryColor,
      gradientColors: gradientColors,
      backgroundImagePath: backgroundImagePath,
      backgroundOpacity: backgroundOpacity,
      isDarkMode: isDarkMode,
      backgroundAlignment: backgroundAlignment,
    );
  }

  /// 从自定义背景图片创建主题
  static Future<AppThemeConfig> fromBackgroundImage(
    String imagePath, {
    double backgroundOpacity = 0.8,
    Alignment? backgroundAlignment,
  }) async {
    // 使用Palette生成器从图片提取主色调
    final imageProvider = FileImage(File(imagePath));
    final paletteGenerator = await PaletteGenerator.fromImageProvider(
      imageProvider,
      size: Size(200, 200), // 缩小尺寸以加快处理速度
    );

    // 获取主色调，如果没有则使用默认粉色
    final dominantColor =
        paletteGenerator.dominantColor?.color ?? Color(0xFFFF4081);

    // 判断是否应该使用暗色模式（基于主色调的亮度）
    final isDarkMode = dominantColor.computeLuminance() < 0.5;

    // 创建渐变色
    final gradientColors = [
      dominantColor.withOpacity(0.8),
      dominantColor,
      HSLColor.fromColor(dominantColor)
          .withLightness(
            (HSLColor.fromColor(dominantColor).lightness + 0.1).clamp(0.0, 1.0),
          )
          .toColor(),
    ];

    return AppThemeConfig.custom(
      primaryColor: dominantColor,
      gradientColors: gradientColors,
      backgroundImagePath: imagePath,
      backgroundOpacity: backgroundOpacity,
      isDarkMode: isDarkMode,
      backgroundAlignment: backgroundAlignment,
    );
  }

  /// 创建副本并更新属性
  AppThemeConfig copyWith({
    AppThemeType? themeType,
    Color? primaryColor,
    List<Color>? gradientColors,
    String? backgroundImagePath,
    double? backgroundOpacity,
    bool? isDarkMode,
    Alignment? backgroundAlignment,
    String? fontFamily,
  }) {
    return AppThemeConfig(
      themeType: themeType ?? this.themeType,
      primaryColor: primaryColor ?? this.primaryColor,
      gradientColors: gradientColors ?? this.gradientColors,
      backgroundImagePath: backgroundImagePath ?? this.backgroundImagePath,
      backgroundOpacity: backgroundOpacity ?? this.backgroundOpacity,
      isDarkMode: isDarkMode ?? this.isDarkMode,
      backgroundAlignment: backgroundAlignment ?? this.backgroundAlignment,
      fontFamily: fontFamily ?? this.fontFamily,
    );
  }

  /// 将主题配置转换为Map
  Map<String, dynamic> toMap() {
    return {
      'themeType': themeType.index,
      'primaryColor': primaryColor.value,
      'gradientColors': gradientColors.map((c) => c.value).toList(),
      'backgroundImagePath': backgroundImagePath,
      'backgroundOpacity': backgroundOpacity,
      'isDarkMode': isDarkMode,
      'backgroundAlignment':
          backgroundAlignment != null
              ? {'x': backgroundAlignment!.x, 'y': backgroundAlignment!.y}
              : null,
      'fontFamily': fontFamily,
    };
  }

  /// 从Map创建主题配置
  factory AppThemeConfig.fromMap(Map<String, dynamic> map) {
    final themeTypeIndex = map['themeType'] as int;
    final themeType = AppThemeType.values[themeTypeIndex];
    final fontFamily = map['fontFamily'] as String? ?? 'Cat';

    // 如果是预设主题，直接返回对应的工厂方法，但保留字体设置
    if (themeType == AppThemeType.pinkGradient) {
      return AppThemeConfig.defaultTheme().copyWith(fontFamily: fontFamily);
    } else if (themeType == AppThemeType.darkTheme) {
      return AppThemeConfig.darkTheme().copyWith(fontFamily: fontFamily);
    } else if (themeType == AppThemeType.greyGradient) {
      return AppThemeConfig.greyGradient().copyWith(fontFamily: fontFamily);
    }

    // 解析颜色
    final primaryColor = Color(map['primaryColor'] as int);
    final gradientColorsList =
        (map['gradientColors'] as List<dynamic>)
            .map((e) => Color(e as int))
            .toList();

    // 解析对齐方式
    Alignment? alignment;
    if (map['backgroundAlignment'] != null) {
      final alignmentMap = map['backgroundAlignment'] as Map<String, dynamic>;
      alignment = Alignment(
        alignmentMap['x'] as double,
        alignmentMap['y'] as double,
      );
    }

    // 创建自定义主题
    return AppThemeConfig(
      themeType: themeType,
      primaryColor: primaryColor,
      gradientColors: gradientColorsList,
      backgroundImagePath: map['backgroundImagePath'] as String?,
      backgroundOpacity: map['backgroundOpacity'] as double,
      isDarkMode: map['isDarkMode'] as bool,
      backgroundAlignment: alignment,
      fontFamily: fontFamily,
    );
  }

  /// 转换为Flutter主题数据
  ThemeData toThemeData() {
    final brightness = isDarkMode ? Brightness.dark : Brightness.light;

    // 创建基础主题数据
    final baseTheme = ThemeData(
      primaryColor: primaryColor,
      primarySwatch: MaterialColor(primaryColor.value, {
        50: primaryColor.withOpacity(0.1),
        100: primaryColor.withOpacity(0.2),
        200: primaryColor.withOpacity(0.3),
        300: primaryColor.withOpacity(0.4),
        400: primaryColor.withOpacity(0.5),
        500: primaryColor.withOpacity(0.6),
        600: primaryColor.withOpacity(0.7),
        700: primaryColor.withOpacity(0.8),
        800: primaryColor.withOpacity(0.9),
        900: primaryColor,
      }),
      brightness: brightness,
      colorScheme: ColorScheme.fromSeed(
        seedColor: primaryColor,
        brightness: brightness,
      ),
      useMaterial3: true,
      // 全局字体设置
      fontFamily: fontFamily,
      // AppBar 主题
      appBarTheme: AppBarTheme(
        centerTitle: true,
        titleTextStyle: TextStyle(
          fontFamily: fontFamily,
          fontSize: 22,
          color: isDarkMode ? Colors.grey.shade200 : Colors.white,
        ),
      ),
      // 文本主题
      textTheme: TextTheme(
        // 用于主标题
        titleLarge: TextStyle(
          fontFamily: fontFamily,
          fontSize: 22,
          fontWeight: FontWeight.bold,
          color: isDarkMode ? Colors.grey.shade200 : Colors.black,
        ),
        // 用于副标题
        titleMedium: TextStyle(
          fontFamily: fontFamily,
          fontSize: 18,
          fontWeight: FontWeight.w500,
          color: isDarkMode ? Colors.grey.shade300 : Colors.black87,
        ),
        // 用于正文
        bodyLarge: TextStyle(
          fontFamily: fontFamily,
          fontSize: 16,
          color: isDarkMode ? Colors.grey.shade300 : Colors.black87,
        ),
        // 用于小号文本
        bodyMedium: TextStyle(
          fontFamily: fontFamily,
          fontSize: 14,
          color: isDarkMode ? Colors.grey.shade400 : Colors.black54,
        ),
        // 用于提示文本
        bodySmall: TextStyle(
          fontFamily: fontFamily,
          fontSize: 12,
          color: isDarkMode ? Colors.grey.shade500 : Colors.grey,
        ),
      ),
    );

    // 根据是否为暗色模式应用不同的样式
    if (isDarkMode) {
      // 暗色模式特定样式
      return baseTheme.copyWith(
        // 调整卡片颜色，减少与背景的对比度
        cardColor: const Color(0xFF2C3E50).withOpacity(0.7),
        // 调整分隔线颜色
        dividerColor: Colors.grey.shade700,
        // 调整列表瓦片颜色
        listTileTheme: ListTileThemeData(
          tileColor: const Color(0xFF2C3E50),
          textColor: Colors.grey.shade300,
          iconColor: primaryColor,
        ),
        // 调整AppBar样式
        appBarTheme: AppBarTheme(
          backgroundColor: const Color(0xFF2C3E50),
          foregroundColor: Colors.grey.shade200,
          elevation: 0,
          centerTitle: true,
          titleTextStyle: TextStyle(
            fontFamily: fontFamily,
            fontSize: 22,
            color: Colors.grey.shade200,
          ),
        ),
        // 调整底部导航栏样式
        bottomNavigationBarTheme: BottomNavigationBarThemeData(
          backgroundColor: const Color(0xFF2C3E50),
          selectedItemColor: primaryColor,
          unselectedItemColor: Colors.grey.shade600,
        ),
        // 调整Scaffold背景色
        scaffoldBackgroundColor: const Color(0xFF1C2833),
      );
    } else {
      // 亮色模式保持原样
      return baseTheme;
    }
  }
}

/// 主题服务类
class ThemeService {
  static const String _prefsKey = 'app_theme_config';

  /// 保存主题配置到本地
  Future<bool> saveThemeConfig(AppThemeConfig config) async {
    try {
      final prefs = await SharedPreferences.getInstance();

      // 保存配置
      final configMap = config.toMap();
      final configString = json.encode(configMap);
      await prefs.setString(_prefsKey, configString);
      return true;
    } catch (e) {
      print('保存主题配置失败: $e');
      return false;
    }
  }

  /// 从本地加载主题配置
  Future<AppThemeConfig> loadThemeConfig() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final configString = prefs.getString(_prefsKey);

      if (configString == null || configString.isEmpty) {
        return AppThemeConfig.defaultTheme();
      }

      try {
        // 尝试解析JSON字符串
        final Map<String, dynamic> configMap = json.decode(configString);
        final config = AppThemeConfig.fromMap(configMap);
        return config;
      } catch (parseError) {
        print('解析主题配置失败: $parseError');
        return AppThemeConfig.defaultTheme();
      }
    } catch (e) {
      print('加载主题配置失败: $e');
      return AppThemeConfig.defaultTheme();
    }
  }

  /// 选择并处理背景图片
  Future<String?> pickBackgroundImage() async {
    try {
      final picker = ImagePicker();
      final pickedFile = await picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 2400,
        maxHeight: 2400,
      );

      if (pickedFile == null) {
        return null;
      }

      // Web平台处理
      if (kIsWeb) {
        try {
          // Web平台直接读取图片数据
          final Uint8List imageBytes = await pickedFile.readAsBytes();

          // 使用image库解码图片
          final img.Image? image = img.decodeImage(imageBytes);

          if (image == null) {
            print('Web平台：无法解码图片');
            return null;
          }

          // 调整图片大小
          final img.Image resizedImage = img.copyResize(
            image,
            width: 1920,
            height: (1920 * image.height / image.width).round(),
          );

          // 在Web平台，我们不能保存到文件系统，所以使用内存中的图片路径
          // 这里使用一个特殊的标记来表示这是Web平台的图片
          final webImagePath =
              'web_image_${DateTime.now().millisecondsSinceEpoch}';

          // 将图片数据存储在SharedPreferences中
          final prefs = await SharedPreferences.getInstance();
          final encodedImage = img.encodeJpg(resizedImage, quality: 90);
          await prefs.setString(
            webImagePath,
            String.fromCharCodes(encodedImage),
          );

          return 'web://$webImagePath';
        } catch (e) {
          print('Web平台处理图片失败: $e');
          return null;
        }
      }

      // 移动平台处理
      // 裁剪图片
      CroppedFile? croppedFile;
      try {
        croppedFile = await _cropImage(pickedFile.path);
        if (croppedFile == null) {
          return null; // 用户取消了裁剪
        }
      } catch (e) {
        print('裁剪图片失败，使用原图: $e');
        // 如果裁剪失败，直接使用原图
        croppedFile = CroppedFile(pickedFile.path);
      }

      // 读取图片并压缩
      File imageFile;
      try {
        imageFile = File(croppedFile.path);
        if (!await imageFile.exists()) {
          print('裁剪后的图片不存在，使用原图');
          imageFile = File(pickedFile.path);
        }
      } catch (e) {
        print('读取裁剪后的图片失败，使用原图: $e');
        imageFile = File(pickedFile.path);
      }

      final img.Image? image = img.decodeImage(await imageFile.readAsBytes());

      if (image == null) {
        print('无法解码图片');
        return null;
      }

      // 压缩图片
      final img.Image resizedImage = img.copyResize(
        image,
        width: 1920,
        height: (1920 * image.height / image.width).round(),
      );

      // 保存压缩后的图片
      final appDir = await getApplicationDocumentsDirectory();
      final fileName = 'bg_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final savedImagePath = '${appDir.path}/$fileName';

      final File savedFile = File(savedImagePath);
      await savedFile.writeAsBytes(img.encodeJpg(resizedImage, quality: 90));

      return savedImagePath;
    } catch (e) {
      print('选择背景图片失败: $e');
      return null;
    }
  }

  /// 裁剪图片
  Future<CroppedFile?> _cropImage(String sourcePath) async {
    // Web平台不支持裁剪，直接返回原图
    if (kIsWeb) {
      return CroppedFile(sourcePath);
    }

    try {
      return await ImageCropper().cropImage(
        sourcePath: sourcePath,
        aspectRatio: const CropAspectRatio(ratioX: 9, ratioY: 16), // 手机屏幕比例
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: '裁剪背景图片',
            toolbarColor: const Color(0xFF5D6D7E),
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.ratio16x9,
            lockAspectRatio: false,
            hideBottomControls: false,
          ),
          IOSUiSettings(
            title: '裁剪背景图片',
            doneButtonTitle: '完成',
            cancelButtonTitle: '取消',
            aspectRatioLockEnabled: false,
          ),
        ],
      );
    } catch (e) {
      print('裁剪图片失败: $e');
      // 如果裁剪失败，直接返回原图
      return CroppedFile(sourcePath);
    }
  }
}

/// 主题配置提供者
final appThemeConfigProvider =
    StateNotifierProvider<AppThemeNotifier, AppThemeConfig>((ref) {
      return AppThemeNotifier();
    });

/// 主题配置状态管理
class AppThemeNotifier extends StateNotifier<AppThemeConfig> {
  final ThemeService _themeService = ThemeService();

  AppThemeNotifier() : super(AppThemeConfig.defaultTheme()) {
    _loadSavedTheme();
  }

  /// 加载保存的主题
  Future<void> _loadSavedTheme() async {
    final savedTheme = await _themeService.loadThemeConfig();
    state = savedTheme;
  }

  /// 切换到预设主题
  Future<void> setPresetTheme(AppThemeType themeType) async {
    // 保存当前字体设置
    final currentFontFamily = state.fontFamily;

    AppThemeConfig newTheme;

    switch (themeType) {
      case AppThemeType.pinkGradient:
        newTheme = AppThemeConfig.defaultTheme();
        break;
      case AppThemeType.darkTheme:
        newTheme = AppThemeConfig.darkTheme();
        break;
      case AppThemeType.greyGradient:
        newTheme = AppThemeConfig.greyGradient();
        break;
      default:
        return; // 不处理自定义主题
    }

    // 应用当前字体设置到新主题
    newTheme = newTheme.copyWith(fontFamily: currentFontFamily);

    state = newTheme;
    await _themeService.saveThemeConfig(newTheme);
  }

  /// 设置自定义背景图片主题
  Future<bool> setCustomBackgroundTheme(
    String imagePath, {
    double opacity = 0.8,
  }) async {
    try {
      // 保存当前字体设置
      final currentFontFamily = state.fontFamily;

      final customTheme = await AppThemeConfig.fromBackgroundImage(
        imagePath,
        backgroundOpacity: opacity,
      );

      // 应用当前字体设置到新主题
      final updatedTheme = customTheme.copyWith(fontFamily: currentFontFamily);

      state = updatedTheme;
      await _themeService.saveThemeConfig(updatedTheme);
      return true;
    } catch (e) {
      print('设置自定义背景主题失败: $e');
      return false;
    }
  }

  /// 更新背景透明度
  Future<void> updateBackgroundOpacity(double opacity) async {
    final updatedTheme = state.copyWith(backgroundOpacity: opacity);
    state = updatedTheme;
    await _themeService.saveThemeConfig(updatedTheme);
  }

  /// 选择并设置新的背景图片
  Future<bool> pickAndSetBackgroundImage({double opacity = 0.8}) async {
    final imagePath = await _themeService.pickBackgroundImage();
    if (imagePath == null) {
      return false;
    }

    return await setCustomBackgroundTheme(imagePath, opacity: opacity);
  }

  /// 设置字体
  Future<void> setFontFamily(String fontFamily) async {
    state = state.copyWith(fontFamily: fontFamily);
    await _themeService.saveThemeConfig(state);
  }
}

/// 全局样式助手类，确保所有组件使用一致的样式
class AppStyleHelper {
  /// 获取标题文本样式
  static TextStyle getTitleStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 22,
    FontWeight fontWeight = FontWeight.bold,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.titleLarge?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.titleLarge?.color,
    );
  }

  /// 获取副标题文本样式
  static TextStyle getSubtitleStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 18,
    FontWeight fontWeight = FontWeight.w500,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.titleMedium?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.titleMedium?.color,
    );
  }

  /// 获取正文文本样式
  static TextStyle getBodyStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 16,
    FontWeight fontWeight = FontWeight.normal,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.bodyLarge?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.bodyLarge?.color,
    );
  }

  /// 获取小号文本样式
  static TextStyle getSmallStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 14,
    FontWeight fontWeight = FontWeight.normal,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.bodyMedium?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.bodyMedium?.color,
    );
  }

  /// 获取超小号文本样式
  static TextStyle getTinyStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 12,
    FontWeight fontWeight = FontWeight.normal,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.bodySmall?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.bodySmall?.color,
    );
  }

  /// 获取文件计数文本样式
  static TextStyle getFileCountStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 11,
    FontWeight fontWeight = FontWeight.w500,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.bodySmall?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? theme.textTheme.bodySmall?.color,
    );
  }

  /// 获取文件信息文本样式
  static TextStyle getFileInfoStyle(
    BuildContext context, {
    Color? color,
    double fontSize = 9,
    FontWeight fontWeight = FontWeight.normal,
  }) {
    final theme = Theme.of(context);
    return TextStyle(
      fontFamily: theme.textTheme.bodySmall?.fontFamily,
      fontSize: fontSize,
      fontWeight: fontWeight,
      color: color ?? Colors.grey[600],
    );
  }
}
